<!DOCTYPE html>
<html lang="zh" xmlns:th="http://www.thymeleaf.org" >
<head>
    <th:block th:include="include :: header('新增证书申请')" />
    <th:block th:include="include :: datetimepicker-css" />
</head>
<body class="white-bg">
<div class="wrapper wrapper-content animated fadeInRight ibox-content">
    <h4 class="form-header h4">证书申请</h4>
    <form class="form-horizontal m" style="width: 800px;" id="form-domain-add">
        <input type="hidden" name="isYzOver" id="isYzOver">
        <input type="hidden" id="dnsCount">
        <input type="hidden" id="rrVal0">
        <input type="hidden" id="rrVal1">
        <div class="row">
            <div class="col-xs-12">
                <div class="form-group" style="display: flex;">
                    <label class=" control-label is-required" style="text-align: left;">加密算法：</label>
                    <div class="">
                        <div style="display: flex; cursor: pointer;">
                            <div id="privateKeyType1" class="inputDiv sed" onclick="removeClassFun('#privateKeyType2', '#privateKeyType1')">
                                RSA
                            </div>
                            <!--<div id="privateKeyType2" class="inputDiv" onclick="removeClassFun('#privateKeyType1', '#privateKeyType2')">
                                ECC
                            </div>-->
                        </div>
                        <input id="privateKeyType" name="privateKeyType" class="form-control" type="hidden">
                    </div>
                </div>
            </div>
            <div class="col-xs-12">
                <div class="form-group" style="display: flex;">
                    <label class="control-label is-required" style="text-align: left;">证书类型：</label>
                    <div class="">
                        <div style="display: flex; cursor: pointer;">
                            <div id="isUniversal1" class="inputDiv sed" onclick="removeClassFun('#isUniversal2','#isUniversal1')">
                                单域名证书
                            </div>
                            <div id="isUniversal2" class="inputDiv" onclick="removeClassFun('#isUniversal1','#isUniversal2')">
                                通配符证书
                            </div>
                        </div>
                        <input id="isUniversal" name="isUniversal" class="form-control" type="hidden">
                    </div>
                </div>
            </div>
            <div class="col-xs-12">
                <div class="form-group" style="display: flex;">
                    <label class="control-label is-required" style="text-align: left;">颁发机构：</label>
                    <div class="">
                        <div style="display: flex; cursor: pointer;">
                            <div class="inputDiv sed" id="issuingAuthority1" onclick="removeClassFun('#issuingAuthority2', '#issuingAuthority3', '#issuingAuthority1')">
                                <div style="width: 130px; height: 35px;">
                                    <img th:src="@{/img/letsencrypt.png}"  alt="Let's Encrypt" style="width: 100%; height: 100%;"/>
                                </div>
                                Let's EncryptSSL
                            </div>
                            <div class="inputDiv" id="issuingAuthority2" onclick="removeClassFun('#issuingAuthority1', '#issuingAuthority3', '#issuingAuthority2')">
                                <div style="width: 130px; height: 35px;">
                                    <img th:src="@{/img/google.png}"  alt="Let's Encrypt" style="width: 95px; height: 32px;"/>
                                </div>
                                GoogleSSL
                            </div>
                            <div class="inputDiv" id="issuingAuthority3" onclick="removeClassFun('#issuingAuthority1','#issuingAuthority2','#issuingAuthority3')">
                                <div style="width: 130px; height: 35px;">
                                    <img th:src="@{/img/zerossl.png}"  alt="Let's Encrypt" style="width: 100%; height: 100%;"/>
                                </div>
                                ZeroSSL
                            </div>
                        </div>
                        <input id="issuingAuthority" name="issuingAuthority" class="form-control" type="hidden">
                        <span class="help-block m-b-none">建议使用：Let's Encrypt厂商提供的证书</span>
                    </div>
                </div>
            </div>
            <div class="col-xs-12">
                <div class="form-group" style="display: flex;">
                    <label class="control-label is-required" style="text-align: left;">证书域名：</label>
                    <div style="width: 500px;">
                        <input style="outline:none;" id="certificateDomain" name="certificateDomain" placeholder="请输入证书域名" class="form-control" type="text" required>
                        <span class="help-block m-b-none">多个域名请用","逗号隔开</span>
                    </div>
                </div>
            </div>
            <div class="col-xs-12">
                <div class="form-group" style="display: flex;">
                    <label class="control-label is-required" style="text-align: left;">续签到期时间：</label>
                    <div style="width: 500px;">
                        <input type="text" name="autoExpiredTime" class="form-control" id="datetimepicker-demo-2" placeholder="yyyy-MM-dd" required>
                        <span class="help-block m-b-none" style="color: red;"><i class="fa fa-info-circle"></i>如果到期了，该证书就停止自动续签、部署</span>
                    </div>
                </div>
            </div>
            <div class="col-xs-12">
                <div class="form-group">
                    <p class="is-required"><text style="color: red;">*</text>&nbsp;请配置以下DNS解析记录(配置成功后，<text style="color: red; font-weight: bold;font-size: 18px;">请勿删除记录</text> )不删除解析记录，自动续签就可以免验证。</p>
                    <div class="table-responsive">
                        <table class="table table-bordered table-striped">
                            <thead>
                            <tr>
                                <th style="width: 88px;">状态</th>
                                <th style="width: 238px;">主机记录</th>
                                <th style="width: 88px;">记录类型</th>
                                <th style="width: 388px;">记录值</th>
                                <th style="width: 88px;">操作</th>
                            </tr>
                            </thead >
                            <tbody id="tableBody">
                            </tbody>
                        </table>
                    </div>
                    <span class="help-block m-b-none" style="color: red; font-weight: bold;" id="checkResult"></span>
                </div>
            </div>
            <div class="col-xs-12">
                <div class="form-group" style="display: flex;">
                    <label class="control-label" style="text-align: left;">备注描述：</label>
                    <div style="width: 500px;">
                        <textarea name="remark" class="form-control"></textarea>
                    </div>
                </div>
            </div>
        </div>
        <div class="col-xs-12">
            <div class="form-group">
                <button type="button" class="btn btn-sm btn-primary" onclick="submitHandler()"><i class="fa fa-paper-plane"></i>立即申请</button>
                <button type="button" class="btn btn-sm btn-warning" onclick="formReset()"><i class="fa fa-refresh"></i>&nbsp;重置表单</button>
                <button type="button" class="btn btn-sm btn-danger" onclick="closeItem()"><i class="fa fa-reply-all"></i>关闭申请</button>
            </div>
        </div>
    </form>
</div>
<th:block th:include="include :: footer" />
<th:block th:include="include :: datetimepicker-js" />
<script th:inline="javascript">
    var prefix = ctx + "SSL/domain1"
    $("#form-apply-add").validate({
        focusCleanup: true
    });

    document.getElementById("certificateDomain").addEventListener("keyup", function(event) {
        const inputValue = event.target.value.replaceAll("。",".").replace(/\s+/g, "").replaceAll("，",",").replace(/\s+/g, "");
        $("#certificateDomain").val(inputValue);
    });
    //设置默认值
    $(function() {
        $("#datetimepicker-demo-2").datetimepicker({
            format: "yyyy-mm-dd",
            minView: "month",
            autoclose: true
        });
        $("#privateKeyType").val("RSA");
        $("#isUniversal").val("N");
        $("#issuingAuthority").val("LetsEncryptSSL");
        //监听值的变化
        $("#privateKeyType1").click(function (){
            $("#privateKeyType").val("RSA");
        })
        $("#privateKeyType2").click(function (){
            $("#privateKeyType").val("ECC");
        })

        $("#isUniversal1").click(function (){
            $("#isUniversal").val("N");
            $("#certificateDomain").attr("placeholder", "请输入您的证书域名");
        })
        $("#isUniversal2").click(function (){
            $("#isUniversal").val("Y");
            $("#certificateDomain").attr("placeholder", "格式举例：【*.domain.com或*.aa.domain.com】");
        })

        $("#issuingAuthority1").click(function (){
            $("#issuingAuthority").val("LetsEncryptSSL");
        })
        $("#issuingAuthority2").click(function (){
            $.modal.msgWarning("开发中...！");
            // $("#issuingAuthority").val("GoogleSSL");
        })
        $("#issuingAuthority3").click(function (){
            $.modal.msgWarning("开发中...！");
            // $("#issuingAuthority").val("ZeroSSL");
        })
        //监听域名input发生变化
        $("#certificateDomain").change(function (e){
            $.modal.loading("数据校验中，请稍后....");
            $.ajax({
                url: prefix + "/applyBefore?domainName="+ e.target.value,
                type: 'get',
                success:function (res){
                    $("#isYzOver").val('N');
                    $("#tableBody").html('');
                    $.modal.closeLoading();
                    if(res.code === 0){
                        $("#dnsCount").val(res.data.length);
                        for(var i=0; i < res.data.length; i ++){
                            $("#tableBody").append("<tr>" +
                                "<td id='yzStatus"+i+"' style='color: red; font-weight: bold;'><i class='fa fa-close'></i>待配置</td>" +
                                "<td style=\"color: #5B89FE;\">"+res.data[i].rrKeyWord+"<i style='margin-left: 9px;' onclick='copyToClipboard(\"" + res.data[i].rrKeyWord + "\")' class='fa fa fa-clone'></i></td>" +
                                "<td style='color: red; font-weight: bold;'>CNAME</td>" +
                                "<td style=\"color: #5B89FE;\">"+res.data[i].rrVal+"<i style='margin-left: 9px;' onclick='copyToClipboard(\"" + res.data[i].rrVal + "\")' class='fa fa fa-clone'></i></td>" +
                                "<td><a class='btn btn-success btn-xs' href='javascript:void(0)' onclick='verifyDNSExist(\"" + e.target.value + "\",\"" + res.data[i].rrKeyWord + "\", \"" + res.data[i].domainName + "\",\"" + res.data[i].rrVal + "\",\"" + i + "\")'><i class='fa fa-paper-plane'></i>&nbsp;验证</a></td>" +
                                "</tr>");
                        }
                    }else{
                        $.modal.msgError(res.msg);
                    }
                },
                field:function (error){
                    $.modal.closeLoading();
                }
            })
        })
    })

    function verifyDNSExist(domainTxt,rrKeyWord,domainName,rrVal, idx){
        $.modal.loading("验证中，请稍后....");
        $.ajax({
            url: prefix + "/verifyDNSExist?domainTxt="+domainTxt+"&domainName="+(rrKeyWord+"."+domainName)+"&rrVal="+rrVal,
            type: 'get',
            success: function (res1) {
                $.modal.closeLoading();
                if(res1.code === 0){
                    $("#yzStatus"+idx).html("<i class='fa fa-check'></i>已配置");
                    $("#yzStatus"+idx).css('color', "#12B980");
                    $("#rrVal"+idx).val("Y");
                    //判断验证个数
                    let dnsCount = parseInt($("#dnsCount").val());
                    if(dnsCount < 2){
                        if($("#rrVal0").val()){
                            $("#isYzOver").val('Y');
                            $("#checkResult").css('color', "#12B980");
                        }
                    }else{
                        if($("#rrVal0").val()&&$("#rrVal1").val()){
                            $("#isYzOver").val('Y');
                            $("#checkResult").css('color', "#12B980");
                        }
                    }
                    $.modal.msgSuccess("验证成功！");
                }else{
                    $.modal.msgWarning("未查询到dns解析记录或记录未生效！");
                }
            },
            field: function (error) {}
        })
    }
    //获取到当前时间戳
    function formatDate(date) {
        const year = date.getFullYear();
        const month = String(date.getMonth() + 1).padStart(2, '0'); // 月份从0开始，需要加1
        const day = String(date.getDate()).padStart(2, '0');
        const hours = String(date.getHours()).padStart(2, '0');
        const minutes = String(date.getMinutes()).padStart(2, '0');
        const seconds = String(date.getSeconds()).padStart(2, '0');
        return `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`;
    }
    //复制数据fa fa-check
    function copyToClipboard(text) {
        var textarea = document.createElement('textarea');
        textarea.style.position = 'fixed';
        textarea.style.opacity = 0;
        textarea.value = text;
        document.body.appendChild(textarea);
        textarea.select();
        document.execCommand('copy');
        document.body.removeChild(textarea);
        $.modal.msgSuccess("复制成功！");
    }
    //效果展示
    function removeClassFun(id1, id2, id3){
        if(id3){
            $.modal.msgWarning("开发中...！");
            // $(id1).removeClass("sed");
            // $(id2).removeClass("sed");
            // $(id3).addClass("sed");
        }else{
            $(id1).removeClass("sed");
            $(id2).addClass("sed");
        }
    }
    //重置表单的方法
    function formReset(){
        $("#certificateDomain").val('');
        $("#certificateDomain").attr("disabled", false);
        $("#tableBody").html('');
        $("#privateKeyType1").click();
        $("#isUniversal1").click();
        $("#issuingAuthority1").click();
    }
    function submitHandler() {
        var data = $("#form-domain-add").serializeArray();
        if ($.validate.form()) {
            var isYz = $("#isYzOver").val();
            if(isYz && isYz === 'Y'){
                $.operate.saveTab(prefix + "/add", data);
            }else{
                $.modal.msgError("请配置DNS解析记录！");
            }
        }
    }
</script>
</body>
<style type="text/css">
    .inputDiv{border: solid 2px #E4E4E7;align-content: center; text-align: center; padding: 5px 18px;position: relative; border-radius: 5px; margin-right: 5px;}
    .sed{border-color: #12B980; color: #12B980;}
</style>
</html>
